package com.punch.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.punch.common.utils.ImageUtil;
import com.punch.common.vo.course.IndexVO;
import com.punch.course.mapper.AppIndexMapper;
import com.punch.course.model.AppIndex;
import com.punch.course.service.IndexService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class IndexServiceImpl implements IndexService {

    @Resource
    private AppIndexMapper appIndexMapper;

    /**
     * app首页分类
     *
     * @return IndexVO
     */
    @Override
    public List<IndexVO> categoryList() {
        QueryWrapper<AppIndex> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AppIndex::getImageType, 0).orderByAsc(AppIndex::getSortBy);
        return getIndex(queryWrapper);
    }

    /**
     * app首页楼层
     *
     * @return IndexVO
     */
    @Override
    public List<IndexVO> floorList() {
        QueryWrapper<AppIndex> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AppIndex::getImageType, 1).orderByAsc(AppIndex::getSortBy);
        return getIndex(queryWrapper);
    }

    @Override
    public IndexVO indexDetail(Long id) {
        AppIndex appIndex = appIndexMapper.selectById(id);
        IndexVO indexVO = new IndexVO();
        indexVO.setId(id);
        indexVO.setTitle(appIndex.getTitle());
        indexVO.setImageUrl(ImageUtil.addPrefix(appIndex.getImageUrl()));
        QueryWrapper<AppIndex> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AppIndex::getImageType, 2).eq(AppIndex::getParentId, id).orderByAsc(AppIndex::getSortBy);
        indexVO.setChildList(getIndex(queryWrapper));
        return indexVO;
    }

    private List<IndexVO> getIndex(QueryWrapper<AppIndex> queryWrapper) {
        List<IndexVO> list = new ArrayList<>();
        appIndexMapper.selectList(queryWrapper).forEach(appIndex -> {
            IndexVO indexVO = new IndexVO();
            indexVO.setId(appIndex.getId());
            indexVO.setTitle(appIndex.getTitle());
            indexVO.setImageUrl(ImageUtil.addPrefix(appIndex.getImageUrl()));
            list.add(indexVO);
        });
        return list;
    }
}
